import {Component, ChangeDetectorRef} from '@angular/core';
import {
    NavController,
    AlertController,
    NavParams,
    ActionSheetController
} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {HttpService} from '../../providers/http.service';
import {WorkSumPage} from '../work-sum/work-sum';
import * as moment from 'moment';
import {CommonFunc} from '../../providers/commonFunc';
import {appConfig} from '../../providers/config';
import {maintUserAdded} from './bean/maintUserAdded.bean';
import {CameraOptions, Camera} from '@ionic-native/camera';
import {FileUploadOptions, FileTransferObject, FileTransfer} from '@ionic-native/file-transfer';
import {PhotoViewer} from '@ionic-native/photo-viewer';
import {HomePage} from '../home/home';


@Component({
    templateUrl: 'maintUserAdd.html',
    providers: [HttpService, CommonFunc]
})
export class MaintUserAddPage {
    appConfig = appConfig
    itemlist = [];
    xcfhcsList = [];
    ldbhList = [];
    elevatorPlace: any;
    otherPlace: any;
    placeType: any;
    oldplaceType: any;
    oldelevatorPlace: any;
    elevatorInfo: any;
    elevatorNum: any;
    user: any;
    public maintUserAdded = new maintUserAdded();
    // 定义其他的拍照照片
    public otherPhotoList:any;


    constructor(
        public navCtrl: NavController,
        private storage: Storage,
        private httpService: HttpService,
        private alert: AlertController,
        private camera: Camera,
        private commonFunc: CommonFunc,
        private transfer: FileTransfer,
        private photoViewer: PhotoViewer,
        private actionSheet: ActionSheetController,
        public cd: ChangeDetectorRef,
        private navParams: NavParams,
    ) {
        this.storage.get('user').then(data => {
            this.user = data;
        })
        this.elevatorInfo = this.navParams.get('elevatorInfo');
        //this.oldplaceType = this.elevatorInfo.placeType;
        //this.placeType = this.elevatorInfo.placeType;
        //this.oldelevatorPlace = this.elevatorInfo.elevatorPlace;
        /*if (this.elevatorInfo.placeType == 0) {
            this.otherPlace = this.elevatorInfo.elevatorPlace;
        }
        if (this.elevatorInfo.placeType == 1) {
            this.elevatorPlace = this.elevatorInfo.elevatorPlace;
        }*/

        if (this.navParams.get('isLook')) {
            let elevatorType = this.navParams.get('ElevaType');
            let elevatorNum = this.navParams.get('elevatorNum');
            this.elevatorNum = this.navParams.get('elevatorNum');
            if (elevatorType == '4' || elevatorType == '6') {
                this.storage.get(elevatorNum + 'escalator-half-mon').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
            if (elevatorType == '3') {
                this.storage.get(elevatorNum + 'debirs-half').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
            if (elevatorType == '2') {
                this.storage.get(elevatorNum + 'hydpress-half').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
            if (elevatorType == '1' || elevatorType == '5') {
                this.storage.get(elevatorNum + 'traction-half').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
        }
    }

    changePlace(type) {
        if (type == 1) {
            this.otherPlace = null;
        } else {
            this.elevatorPlace = null;
        }
    }

    doSubmit() {
        if (this.navParams.get('isLook')) {
            let toas = this.commonFunc.showInsideErrorToast({
                errorMessage: '已提交维保记录不能修改'
            });
            toas.present();
            return;
        }
        this.otherPhotoList = this.maintUserAdded.other.picUrl;
        /*if (!this.placeType || (!this.otherPlace && !this.elevatorPlace)) {
            let toas = this.commonFunc.showInsideErrorToast({
                errorMessage: '电梯所在场所不能为空'
            });
            toas.present();
            return;
        }
        if (this.placeType == 0) {
            this.elevatorPlace = this.otherPlace;
        }
        if (this.oldplaceType != this.placeType ||
            this.oldelevatorPlace != this.elevatorPlace) {
            let param = {
                id: this.elevatorInfo.id,
                placeType: this.placeType,
                elevatorPlace: this.elevatorPlace
            }
            this.httpService.updateElevatorPlace(param).subscribe(data => {
                console.log(JSON.stringify(data));
            });
        }*/
        this.navCtrl.push(WorkSumPage, {
            ElevaType: this.navParams.get('ElevaType'),
            elevatorInfo: this.navParams.get('elevatorInfo'),
            date: this.navParams.get("date"),
            maintUserAddedList: this.itemlist,
            xcfhcs: this.navParams.get("xcfhcs"),
            ldbh: this.navParams.get("ldbh"),
            elevatorPlace: this.elevatorPlace,
            // 其他照片的集合
            otherPhotos:this.otherPhotoList,
        });
    }

    //缓存
    cache() {

       /* if (!this.placeType || (!this.otherPlace && !this.elevatorPlace)) {
            let toas = this.commonFunc.showInsideErrorToast({
                errorMessage: '电梯所在场所不能为空'
            });
            toas.present();
            return;
        }
        if (this.placeType == 0) {
            this.elevatorPlace = this.otherPlace;
        }
        if (this.oldplaceType != this.placeType ||
            this.oldelevatorPlace != this.elevatorPlace) {
            let param = {
                id: this.elevatorInfo.id,
                placeType: this.placeType,
                elevatorPlace: this.elevatorPlace
            }
            this.httpService.updateElevatorPlace(param).subscribe(data => {
                console.log(JSON.stringify(data));
            });
        }*/


        let datas = new Date().getTime();
        let maintenancenUsedTime =
            Math.floor((datas - this.navParams.get('data')) / (60 * 1000)) + 1 + '';
        let maintenanceEndDate = moment(datas).format('YYYYMMDDHHmmss');
        let maintenanceStartDate = moment(this.navParams.get('data')).format('YYYYMMDDHHmmss');
        let bsData = {
            ElevaType: this.navParams.get('ElevaType'),
            elevatorInfo: this.navParams.get('elevatorInfo'),
            data: this.navParams.get('data'),
            maintUserAddedList: this.itemlist,
            xcfhcs: this.xcfhcsList,
            ldbh: this.ldbhList,
            maintenanceStartDate: maintenanceStartDate,
            maintenanceEndDate: maintenanceEndDate,
            maintenancenUsedTime: maintenancenUsedTime
        }
        let cacheData = {
            bsData: bsData,
            elevatorNum: this.elevatorNum,
            outsideNum: this.navParams.get('elevatorInfo').outsideNum,
            userName: this.user.userName,
            dateTime: maintenanceEndDate
        }

        this.storage.get(this.user.id + 'cache').then(data => {
            if (data && data.length > 0) {
                data.push({dateTime: maintenanceEndDate, cacheData: cacheData})
            } else {
                this.storage.set(this.user.id + 'cache', [{
                    dateTime: maintenanceEndDate,
                    elevatorNum: this.elevatorNum,
                    cacheData: cacheData
                }]);
            }
        })


        this.navCtrl.setRoot(HomePage).then(data => {
            const alert1 = this.alert.create({
                title: "提示",
                subTitle: "已暂存到手机本地，请记得提交",
                buttons: ["确定"]
            });
            alert1.present();
            return;
        })
    }

    add() {
        this.itemlist.push(new maintUserAdded());
        this.cd.detectChanges();
    }

    delete(index) {
        this.itemlist.splice(index, 1);
        this.cd.detectChanges();
    }

    doOk(i) {
        this.itemlist[i].result.isOk = !this.itemlist[i].result.isOk;
        this.cd.detectChanges();
    }

    whaturl(url) {
        if ((url + '').indexOf('file') < 0) {
            return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
        } else {
            return url;
        }
    }

    doCamera(index, i) {
        let options: CameraOptions = {
            quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
            // encodingType: this.camera.EncodingType.JPEG,
            mediaType: this.camera.MediaType.PICTURE,
            targetWidth: 1500,
            targetHeight: 1500,
            correctOrientation: true
        };
        this.camera.getPicture(options).then(imageData => {
            //判断网络状态
            if (!this.commonFunc.hasNetWork()) {
                if (i == 'c') {
                    this.itemlist[index].result.picUrl.push(imageData);
                } else {
                    this.itemlist[index].result.picUrl[i] = imageData;
                }
                return;
            }
            const options: FileUploadOptions = {};
            let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
            //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
            options.fileKey = 'file';
            options.fileName = 'test.jpg';
            options.mimeType = 'image/jpeg';
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                let aa = JSON.parse(restul['response']);
                if (aa['status'] == 200) {
                    if (aa['data'].length > 0) {
                        if (i == 'c') {
                            this.itemlist[index].result.picUrl.push(aa['data']);
                        } else {
                            this.itemlist[index].result.picUrl[i] = aa['data'];
                        }
                    }
                }
                this.cd.detectChanges();
            });
        });
    }

    onHold(index, param) {
        let actionSheet = this.actionSheet.create({
            buttons: [
                {
                    text: '重拍',
                    role: '重拍',
                    handler: () => {
                        let i = this.itemlist[index].result.picUrl.indexOf(param);
                        this.doCamera(index, i);
                    }
                },
                {
                    text: '查看大图',
                    role: '查看大图',
                    handler: () => {
                        this.photoViewer.show(
                            encodeURI(this.whaturl(param)).replace('%5C', '/'),
                            null,
                            {
                                share: false
                            }
                        );
                    }
                },
                {
                    text: '删除',
                    handler: () => {
                        let i = this.itemlist[index].result.picUrl.indexOf(param);
                        this.itemlist[index].result.picUrl.splice(i, 1);
                    }
                },
                {
                    text: '取消',
                    role: '取消',
                    handler: () => {
                        //console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }

    /**
     * 点击其他获取数据
     */
    otherCamera(name, i) {
        let options: CameraOptions = {
            quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
            // encodingType: this.camera.EncodingType.JPEG,
            mediaType: this.camera.MediaType.PICTURE,
            targetWidth: 1500,
            targetHeight: 1500,
            correctOrientation: true
        };
        this.camera.getPicture(options).then(imageData => {
            //判断网络状态
            if (!this.commonFunc.hasNetWork()) {
                if (i == 'c') {
                    this.maintUserAdded[name].picUrl.push(imageData);
                } else {
                    this.maintUserAdded[name].picUrl[i] = imageData;
                }
                return;
            }
            const options: FileUploadOptions = {};
            let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
            //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
            options.fileKey = 'file';
            options.fileName = 'test.jpg';
            options.mimeType = 'image/jpeg';
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                let aa = JSON.parse(restul['response']);
                if (aa['status'] == 200) {
                    if (aa['data'].length > 0) {
                        if (i == 'c') {
                            this.maintUserAdded[name].picUrl.push(aa["data"]);
                        } else {
                            this.maintUserAdded[name].picUrl[i] = aa["data"];
                        }
                    }
                }
                this.cd.detectChanges();
            });
        });
    }

    /**
     * 点击其他拍照时触发
     * @param name
     * @param param
     */
    onOtherHold(name, param) {
        let actionSheet = this.actionSheet.create({
            buttons: [
                {
                    text: "重拍",
                    role: "重拍",
                    handler: () => {
                        let i = this.maintUserAdded[name].picUrl.indexOf(param);
                        this.otherCamera(name, i);
                    }
                },
                {
                    text: "查看大图",
                    role: "查看大图",
                    handler: () => {
                        let url: string = param;
                        this.photoViewer.show(
                            encodeURI(
                                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
                            ).replace("%5C", "/"),
                            "",
                            {share: false}
                        );
                    }
                },
                {
                    text: "删除",
                    handler: () => {
                        let i = this.maintUserAdded[name].picUrl.indexOf(param);
                        this.maintUserAdded[name].picUrl.splice(i, 1);
                    }
                },
                {
                    text: "取消",
                    role: "取消",
                    handler: () => {
                    }
                }
            ]
        });
        actionSheet.present();
    }

    /**
     * 点击其他拍照时触发
     */
    whatOtherurl(url) {
        if ((url + "").indexOf("file") < 0) {
            return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
        } else {
            return url;
        }
    }



}